import "./reset.css";
import dayjs from "dayjs";
import roleForm from "../form/role.vue";
import editForm from "../form/index.vue";
// import { zxcvbn } from "@zxcvbn-ts/core";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import croppingUpload from "../upload.vue";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps, RoleFormItemProps } from "../utils/types";
import { hideTextAtIndex, getKeyList, isAllEmpty } from "@pureadmin/utils";
// import {
//   getRoleIds,
//   getDeptList,
//   getUserList,
//   getAllRoleList
// } from "@/api/system";
import {
  queryUser,
  createUser,
  updateUser,
  deleteUser,
  type UserInfo
} from "../server";
import { queryDept } from "../../dept/server";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElProgress,
  ElMessageBox
} from "element-plus";
import {
  type Ref,
  h,
  ref,
  toRaw,
  watch,
  computed,
  reactive,
  onMounted
} from "vue";

export function useUser(tableRef: Ref, treeRef: Ref) {
  const form = reactive({
    // 左侧部门树选中的部门名称
    department: "",
    username: "",
    phone: "",
    status: ""
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  // 上传头像信息
  const avatarInfo = ref();
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const higherDeptOptions = ref();
  const treeData = ref([]);
  const treeLoading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    // {
    //   label: "勾选列", // 如果需要表格多选，此处label必须设置
    //   type: "selection",
    //   fixed: "left",
    //   reserveSelection: true // 数据刷新后保留选项
    // },
    {
      label: "用户编号",
      prop: "id",
      width: 90
    },
    // {
    //   label: "用户头像",
    //   prop: "avatar",
    //   cellRenderer: ({ row }) => (
    //     <el-image
    //       fit="cover"
    //       preview-teleported={true}
    //       src={row.avatar}
    //       preview-src-list={Array.of(row.avatar)}
    //       class="w-[24px] h-[24px] rounded-full align-middle"
    //     />
    //   ),
    //   width: 90
    // },
    {
      label: "用户名称",
      prop: "name",
      minWidth: 130
    },
    // {
    //   label: "用户昵称",
    //   prop: "nickname",
    //   minWidth: 130
    // },
    {
      label: "性别",
      prop: "sex",
      minWidth: 90,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.sex === 1 ? "danger" : ""}
          effect="plain"
        >
          {row.sex === 1 ? "女" : "男"}
        </el-tag>
      )
    },
    {
      label: "部门",
      prop: "department",
      minWidth: 90
    },
    {
      label: "职位",
      prop: "position",
      minWidth: 90
    },
    {
      label: "邮箱",
      prop: "email",
      minWidth: 120
    },
    // {
    //   label: "角色",
    //   prop: "roles",
    //   minWidth: 90
    // },
    {
      label: "手机号码",
      prop: "phone",
      minWidth: 90,
      formatter: ({ phone }) => hideTextAtIndex(phone, { start: 3, end: 6 })
    },
    // {
    //   label: "状态",
    //   prop: "status",
    //   minWidth: 90,
    //   cellRenderer: scope => (
    //     <el-switch
    //       size={scope.props.size === "small" ? "small" : "default"}
    //       loading={switchLoadMap.value[scope.index]?.loading}
    //       v-model={scope.row.status}
    //       active-value={1}
    //       inactive-value={0}
    //       active-text="已启用"
    //       inactive-text="已停用"
    //       inline-prompt
    //       style={switchStyle.value}
    //       onChange={() => onChange(scope as any)}
    //     />
    //   )
    // },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "createTime",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });
  const pwdProgress = [
    { color: "#e74242", text: "非常弱" },
    { color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  // 当前密码强度（0-4）
  const curScore = ref();
  const roleOptions = ref([]);

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.username
      }</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          message("已成功修改用户状态", {
            type: "success"
          });
        }, 300);
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  function handleUpdate(row) {
    console.log(row);
  }

  async function handleDelete(row) {
    try {
      const result = await deleteUser({ id: row.id });
      if (result.code === 2000) {
        message(`删除用户成功`, { type: "success" });
        onSearch(); // 刷新列表
      } else {
        message(result.message || "删除用户失败", { type: "error" });
      }
    } catch (error) {
      console.error("删除用户失败:", error);
      message("删除用户失败", { type: "error" });
    }
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    pagination.currentPage = 1; // 重置到第一页
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  async function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    if (curSelected.length === 0) {
      message("请选择要删除的用户", { type: "warning" });
      return;
    }

    try {
      // 并发删除所有选中的用户
      const deletePromises = curSelected.map(user =>
        deleteUser({ id: user.id })
      );
      const results = await Promise.allSettled(deletePromises);

      let successCount = 0;
      let failCount = 0;

      results.forEach((result, index) => {
        if (result.status === "fulfilled" && result.value.code === 2000) {
          successCount++;
        } else {
          failCount++;
          console.error(
            `删除用户 ${curSelected[index].username} 失败:`,
            result
          );
        }
      });

      if (successCount > 0) {
        message(
          `成功删除 ${successCount} 个用户${
            failCount > 0 ? `，${failCount} 个删除失败` : ""
          }`,
          {
            type: successCount === curSelected.length ? "success" : "warning"
          }
        );
      } else {
        message("批量删除失败", { type: "error" });
      }

      // 清空选择并刷新列表
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    } catch (error) {
      console.error("批量删除失败:", error);
      message("批量删除失败", { type: "error" });
    }
  }

  async function onSearch() {
    loading.value = true;
    try {
      const params: any = {
        page: pagination.currentPage,
        per_page: pagination.pageSize
      };

      // 添加部门过滤条件
      if (form.department) {
        params.department = form.department;
      }

      // 如果有搜索条件，添加到参数中（这里需要根据实际接口调整）
      if (form.username) {
        // 由于接口不支持按用户名搜索，这里暂时注释
        // params.username = form.username;
      }

      const result = await queryUser(params);

      if (result.code === 2000) {
        // 数据映射：将接口返回的数据映射到表格需要的格式
        const mappedData = Array.isArray(result.data)
          ? result.data.map((user: UserInfo) => ({
              id: user.id,
              username: user.name, // 接口返回name，表格显示为username
              nickname: user.name, // 使用name作为nickname
              name: user.name, // 使用name作为name
              phone: user.phone,
              email: user.email,
              sex: 0, // 接口没有性别字段，设默认值
              status: 1, // 接口没有状态字段，设默认值
              department: user.department || "未分配部门",
              remark: user.description || "",
              roles: user.roles || "",
              position: user.position || "",
              oa_user: user.oa_user || ""
            }))
          : [];

        dataList.value = mappedData;

        // 更新分页信息
        if (result.pagination) {
          pagination.total = result.pagination.total;
          pagination.currentPage = result.pagination.page;
          pagination.pageSize = result.pagination.per_page;
        } else {
          pagination.total = mappedData.length;
        }
      } else {
        message(result.message || "查询用户失败", { type: "error" });
        dataList.value = [];
        pagination.total = 0;
      }
    } catch (error) {
      console.error("查询用户失败:", error);
      message("查询用户失败", { type: "error" });
      dataList.value = [];
      pagination.total = 0;
    } finally {
      loading.value = false;
    }
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.department = "";
    treeRef.value.onTreeReset();
    onSearch();
  };

  function onTreeSelect({ name, selected }) {
    form.department = selected ? name : "";
    onSearch();
  }

  // 部门选项不再需要树形处理，直接返回部门列表

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}用户`,
      props: {
        formInline: {
          title,
          higherDeptOptions: higherDeptOptions.value || [],
          id: row?.id ?? undefined,
          nickname: row?.nickname ?? "",
          username: row?.username ?? "",
          password: row?.password ?? "",
          phone: row?.phone ?? "",
          email: row?.email ?? "",
          sex: row?.sex ?? "",
          status: row?.status ?? 1,
          remark: row?.remark ?? "",
          department: row?.department ?? "",
          position: row?.position ?? "",
          roles: row?.roles ?? "",
          oa_user: row?.oa_user ?? "",
          name: row?.username ?? ""
        }
      },
      width: "46%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm as any, { ref: formRef }),
      beforeSure: async (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        FormRef.validate(async valid => {
          if (valid) {
            console.log(valid, "curData", curData);
            // return;

            try {
              if (title === "新增") {
                // 调用新增用户接口
                const createData = {
                  name: curData.name,
                  phone: String(curData.phone || ""),
                  department: curData.parentId || "",
                  position: curData.position || "",
                  email: curData.email,
                  roles: curData.roles || "",
                  description: curData.remark || "",
                  oa_user: curData.oa_user || "",
                  password: curData.password
                };
                const result = await createUser(createData as any);
                if (result.code === 2000) {
                  message(`新增用户成功`, { type: "success" });
                  done(); // 关闭弹框
                  onSearch(); // 刷新表格数据
                } else {
                  message(result.message || "新增用户失败", { type: "error" });
                }
              } else {
                // 调用修改用户接口
                const updateData = {
                  id: curData.id,
                  name: curData.name,
                  phone: String(curData.phone || ""),
                  department: curData.department || "",
                  position: curData.position || "",
                  email: curData.email,
                  roles: curData.roles || "",
                  description: curData.remark || "",
                  oa_user: curData.oa_user || ""
                };
                // 如果有新密码，添加到更新数据中
                if (curData.password) {
                  (updateData as any).password = curData.password;
                }
                const result = await updateUser(updateData as any);
                if (result.code === 2000) {
                  message(`修改用户成功`, { type: "success" });
                  done(); // 关闭弹框
                  onSearch(); // 刷新表格数据
                } else {
                  message(result.message || "修改用户失败", { type: "error" });
                }
              }
            } catch (error) {
              console.error(`${title}用户失败:`, error);
              message(`${title}用户失败`, { type: "error" });
            }
          }
        });
      }
    });
  }

  const cropRef = ref();
  /** 上传头像 */
  function handleUpload(row) {
    addDialog({
      title: "裁剪、上传头像",
      width: "40%",
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(croppingUpload, {
          ref: cropRef,
          imgSrc: row.avatar,
          onCropper: info => (avatarInfo.value = info)
        }),
      beforeSure: done => {
        console.log("裁剪后的图片信息：", avatarInfo.value);
        // 根据实际业务使用avatarInfo.value和row里的某些字段去调用上传头像接口即可
        done(); // 关闭弹框
        onSearch(); // 刷新表格数据
      },
      closeCallBack: () => cropRef.value.hidePopover()
    });
  }

  // watch(
  //   pwdForm,
  //   ({ newPwd }) =>
  //     (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  // );

  /** 重置密码 */
  function handleReset(row) {
    addDialog({
      title: `重置 ${row.username} 用户的密码`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => (
        <template>
          <ElForm ref={ruleFormRef} model={pwdForm}>
            <ElFormItem
              prop="newPwd"
              rules={[
                {
                  required: true,
                  message: "请输入新密码",
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={pwdForm.newPwd}
                placeholder="请输入新密码"
              />
            </ElFormItem>
          </ElForm>
          <div class="mt-4 flex">
            {pwdProgress.map(({ color, text }, idx) => (
              <div
                class="w-[19vw]"
                style={{ marginLeft: idx !== 0 ? "4px" : 0 }}
              >
                <ElProgress
                  striped
                  striped-flow
                  duration={curScore.value === idx ? 6 : 0}
                  percentage={curScore.value >= idx ? 100 : 0}
                  color={color}
                  stroke-width={10}
                  show-text={false}
                />
                <p
                  class="text-center"
                  style={{ color: curScore.value === idx ? color : "" }}
                >
                  {text}
                </p>
              </div>
            ))}
          </div>
        </template>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: done => {
        ruleFormRef.value.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            message(`已成功重置 ${row.username} 用户的密码`, {
              type: "success"
            });
            console.log(pwdForm.newPwd);
            // 根据实际业务使用pwdForm.newPwd和row里的某些字段去调用重置用户密码接口即可
            done(); // 关闭弹框
            onSearch(); // 刷新表格数据
          }
        });
      }
    });
  }

  /** 分配角色 */
  async function handleRole(row) {
    // 选中的角色列表
    // const ids = (await getRoleIds({ userId: row.id })).data ?? [];
    const ids = []; // 暂时使用空数组，待后续实现角色接口
    addDialog({
      title: `分配 ${row.username} 用户的角色`,
      props: {
        formInline: {
          username: row?.username ?? "",
          nickname: row?.nickname ?? "",
          roleOptions: roleOptions.value ?? [],
          ids
        }
      },
      width: "400px",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(roleForm, {
          formInline: {
            username: row?.username ?? "",
            nickname: row?.nickname ?? "",
            roleOptions: roleOptions.value ?? [],
            ids
          }
        }),
      beforeSure: (done, { options }) => {
        const curData = options.props.formInline as RoleFormItemProps;
        console.log("curIds", curData.ids);
        // 根据实际业务使用curData.ids和row里的某些字段去调用修改角色接口即可
        done(); // 关闭弹框
      }
    });
  }

  onMounted(async () => {
    treeLoading.value = true;
    onSearch();

    try {
      // 获取部门列表
      const deptResult = await queryDept({
        page: 1,
        per_page: 1000
      });
      if (deptResult.code === 2000) {
        higherDeptOptions.value = deptResult.data || [];
        // 暂时使用相同数据作为树形数据，后续如果需要左侧部门树可以单独处理
        treeData.value = handleTree(deptResult.data || []);
      } else {
        console.error("获取部门列表失败:", deptResult.message);
        higherDeptOptions.value = [];
        treeData.value = [];
      }
    } catch (error) {
      console.error("获取部门列表异常:", error);
      higherDeptOptions.value = [];
      treeData.value = [];
    }

    treeLoading.value = false;

    // 角色列表
    // roleOptions.value = (await getAllRoleList()).data;
  });

  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    onTreeSelect,
    handleUpdate,
    handleDelete,
    handleUpload,
    handleReset,
    handleRole,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
